package com.app.util.common;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;



/**
 * @ClassName: ConvertHtml
 * @Description: 访问JSP转换HTML格式的办理单
 * @author Zhi.Hong
 * @company www.suncn.com.cn
 * @date 2018年3月23日 下午12:58:59
 */
public class ConvertHtml {
	
	/**
	 * @param uri  jsp访问路径
	 * @param path html生成路径
	 * @throws Exception
	 */
	public static  String  createHtml(String uri,String path) throws Exception {
		try{
		
			//根据路径生成文件
			File dirFile = new File(path.substring(0,path.lastIndexOf("/"))); 
			boolean bFile = dirFile.exists(); 
			if(!bFile){
				bFile = dirFile.mkdirs();
			}else {
				System.out.println("文件夹已存在,无需创建!");
			}
			
			//通过URL访问jsp
			System.out.println("-----uri-----"+uri);
			System.out.println("-----path-----"+path);
			
			URL url = new URL(uri);  
			HttpURLConnection uc = (HttpURLConnection) url.openConnection();
			uc.setReadTimeout(240000);
			uc.setConnectTimeout(240000);
			
	    	DataInputStream in = new DataInputStream(uc.getInputStream());
	    	DataOutputStream out=new DataOutputStream(new FileOutputStream(path));
	    	byte[] buffer = new byte[4096];
	    	int count = 0;
	    	while ((count = in.read(buffer)) > 0) {
	    	    out.write(buffer, 0, count);
	    	}
	    	out.close();
	    	in.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}
			return path;
	}
	
	/**
     * 发送 get请求
     */
    public static String doGet(String url,String code) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
       
        String result = "";
        try {
        	
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            
            String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
            httpget.setHeader("User-Agent",userAgent);
            
            
            // 执行get请求.
            RequestConfig requestConfig = RequestConfig.custom()
            							  .setSocketTimeout(10000)
            							  .setConnectTimeout(10000)
            							  .build();//设置请求和传输超时时间
            
            if(code != null && !code.equals("")) {
            	httpget.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, code); 
            }
            

            httpget.setConfig(requestConfig);
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    
                	if(code != null && !code.equals("")) {
                		String content = EntityUtils.toString(entity,code);
                       // result = new String(content.getBytes("ISO-8859-1"),code);
                		result = content;
                	}else {
                		result = EntityUtils.toString(entity);
                	}
                    //result = EntityUtils.toString(entity);
                    
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return result;
    }
    
    private static void writeFile(String strContent,String filePath,String fileName){
    	try {  
    		File file_dir = new File(filePath);  
    		if (!file_dir.exists()){
    			file_dir.mkdirs();
    		}
    	         
    		System.out.println(filePath+fileName+"============");
            File f = new File(filePath+fileName);  
        	if (f.exists()) {  
            } else {  
                f.createNewFile();// 不存在则创建  
            }  
  
            BufferedWriter output = new BufferedWriter(new FileWriter(f));  
            output.write(strContent);  
            output.close(); 
             
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
    }
}
